package main

import (
    "fmt"
    "net"
    "net/http"
    "io/ioutil"
)

func sayHello(w http.ResponseWriter, r *http.Request) {
    b, _ := ioutil.ReadFile("./hello.html")
    _, _ = fmt.Fprintln(w, string(b))
}

func sayWorld(w http.ResponseWriter, r *http.Request) {
    _, _ = fmt.Fprintln(w, "<h1>World Golang!</h1>")
}

var localIP string

const (
    XForwardedFor = "X-Forwarded-For"
    XRealIP       = "X-Real-IP"
)

// 获取本机网卡IP
func GetLocalIP() (ip string, err error) {
    addrs, err := net.InterfaceAddrs()
    if err != nil {
        return
    }
    for _, addr := range addrs {
        ipAddr, ok := addr.(*net.IPNet)
        if !ok {
            continue
        }
        if ipAddr.IP.IsLoopback() {
            continue
        }
        if !ipAddr.IP.IsGlobalUnicast() {
            continue
        }
        return ipAddr.IP.String(), nil
    }
    return
}

// RemoteIp 返回远程客户端的 IP
func RemoteIp(wrt http.ResponseWriter, req *http.Request) {
    remoteAddr := req.RemoteAddr
    if ip := req.Header.Get(XRealIP); ip != "" {
        remoteAddr = ip
    } else if ip = req.Header.Get(XForwardedFor); ip != "" {
        remoteAddr = ip
    } else {
        remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
    }

    if remoteAddr == "::1" {
        remoteAddr = "127.0.0.1"
    }
    localIP, _ := GetLocalIP()
    _, _ = fmt.Fprintln(wrt, "<h1>Server_IP: "+localIP+"</h1>\n<h1>Client_IP: "+remoteAddr+"</h1>")
}

func main() {
    // 1. 新增：映射静态文件目录（关键修复）
    // 将本地的 "images" 目录映射到 HTTP 路径 "/images"
    // 当浏览器请求 /images/xxx 时，会自动读取本地 images/xxx 文件
    http.Handle("/images/", http.StripPrefix("/images/", 
        http.FileServer(http.Dir("./images"))))

    // 2. 原有路由配置（保持不变）
    http.HandleFunc("/hello", sayHello)
    http.HandleFunc("/world", sayWorld)
    http.HandleFunc("/info", RemoteIp)

    // 3. 启动服务（监听9999端口）
    err := http.ListenAndServe(":9999", nil)
    if err != nil {
        fmt.Printf("http serve failed, err:%v\n", err)
        return
    }
}
